<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          保存到草稿
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <!--          <Warning />-->

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                文章标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="作者:" class="postInfo-container-item">
                    <el-select v-model="postForm.authorId" :remote-method="getRemoteUserList" filterable default-first-option remote placeholder="查找作者">
                      <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="120px" label="文章分类:" class="postInfo-container-item">
                    <el-select v-model="postForm.categoryId" :remote-method="getRemoteCategoryList" filterable default-first-option remote placeholder="查找分类">
                      <el-option v-for="(item,index) in categoryListOptions" :key="item+index" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!--                <el-col :span="10">-->
                <!--                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">-->
                <!--                    <el-date-picker v-model="displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间" />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="文章封面:" class="postInfo-container-item">
                    <el-upload
                      action="http://192.168.0.28:8899/file/upload"
                      list-type="picture-card"
                      :limit="1"
                      :file-list="fileList"
                      :on-preview="handlePictureCardPreview"
                      :on-exceed="handleExceed"
                      :on-success="handleSuccess"
                      :on-remove="handleRemove"
                    >
                      <i class="el-icon-plus" />
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row hidden>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="文章封面:" class="postInfo-container-item">
                    <el-input v-model="postForm.coverImageUrl" placeholder="标题" style="width: 200px;" class="filter-item" />
                  </el-form-item>
                </el-col>
                <!--                <el-col :span="10">-->
                <!--                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">-->
                <!--                    <el-date-picker v-model="displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间" />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="摘要:">
          <el-input v-model="postForm.summary" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入内容" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.context" :height="400" />
        </el-form-item>

        <!--        <el-form-item prop="image_uri" style="margin-bottom: 30px;">-->
        <!--          <Upload v-model="postForm.image_uri" />-->
        <!--        </el-form-item>-->
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchArticle, createArticle, updateArticle } from '@/api/article/article-info'
import { searchCategory } from '@/api/article/article-cat'
import { searchUser } from '@/api/article/article-user'

const defaultForm = {
  status: 'draft',
  title: '', // 文章题目
  content: '', // 文章内容
  content_short: '', // 文章摘要
  source_uri: '', // 文章外链
  image_uri: '', // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      categoryListOptions: [],
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      fileTemp: {
        url: ''
      },
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ required: true, message: '标题为必填项', trigger: 'blur' }],
        summary: [{ required: true, message: '摘要为必填项', trigger: 'blur' }],
        context: [{ required: true, message: '内容为必填项', trigger: 'blur' }],
        authorId: [{ required: true, message: '作者为必填项', trigger: 'blur' }],
        categoryId: [{ required: true, message: '分类为必填项', trigger: 'blur' }]
        // source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    lang() {
      return this.$store.getters.language
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.postForm.display_time))
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
    this.getRemoteUserList(undefined)
    this.getRemoteCategoryList(undefined)
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
      return
    },
    handleSuccess(response, file) {
      this.postForm.coverImageUrl = response.url
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    fetchData(id) {
      fetchArticle(id).then(response => {
        this.postForm = response.data

        // just for test
        this.postForm.title += ``
        this.postForm.content_short += `${this.postForm.id}`
        this.fileTemp.url = this.postForm.coverImageUrl
        this.fileList.push(this.fileTemp)

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    resetForm() {
      this.postForm.title = undefined
      this.postForm.summary = undefined
      this.postForm.authorId = undefined
      this.postForm.categoryId = undefined
      this.postForm.context = ''
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true

          this.postForm.infoMark = 1
          if (this.postForm.id == null) {
            createArticle(this.postForm).then(response => {
              console.log(JSON.stringify(response))
              if (response.code === 20000) {
                this.$notify({
                  title: '成功',
                  message: '发布文章成功',
                  type: 'success',
                  duration: 2000
                })
                this.postForm.id = response.data
              }
              this.loading = false
            })
          } else {
            updateArticle(this.postForm).then(response => {
              if (response.code === 20000) {
                this.$notify({
                  title: '成功',
                  message: '发布文章成功',
                  type: 'success',
                  duration: 2000
                })
              }
              this.loading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.context.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.loading = true

      if (this.postForm.id != null) {
        this.postForm.status = 'draft'
        this.postForm.infoMark = 0
        updateArticle(this.postForm).then(response => {
          if (response.code === 20000) {
            this.$notify({
              title: '成功',
              message: '文章已存入草稿箱',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        this.postForm.status = 'draft'
        this.postForm.infoMark = 0
        createArticle(this.postForm).then(response => {
          if (response.code === 20000) {
            this.$notify({
              title: '成功',
              message: '文章已存入草稿箱',
              type: 'success',
              duration: 2000
            })
            this.postForm.id = response.data
          }
        })
      }
      this.loading = false
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data) return
        this.userListOptions = response.data
      })
    },
    getRemoteCategoryList(query) {
      searchCategory(query).then(response => {
        if (!response.data) return
        this.categoryListOptions = response.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
